from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser, BaseUserManager
import os
from uuid import uuid4
import time
from django.conf import settings


# 生成唯一文件名
def uuid_file_path_for_avatar(instance, filename):
    ext = filename.split('.')[-1]  # 获取文件扩展名
    filename = f'{uuid4()}.{ext}'  # 使用 UUID 生成新的文件名
    # 获取上传文件的目录路径，这里假设你想要保存在项目根目录下的 media 文件夹中 
    return os.path.join('avatar', filename)  # 返回文件路径


# 生成唯一文件名
def uuid_file_path(instance, filename):
    ext = filename.split('.')[-1]  # 获取文件扩展名
    filename = f'{uuid4()}.{ext}'  # 使用 UUID 生成新的文件名
    # 获取上传文件的目录路径，这里假设你想要保存在项目根目录下的 media 文件夹中
    directory = os.path.join('media', 'topic')  
    return os.path.join('topic', filename)  # 返回文件路径


class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError('The Username field must be set')
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self.create_user(username, password, **extra_fields)

class User(AbstractBaseUser):
    username = models.CharField(max_length=150, unique=True, verbose_name='用户名')
    nickname = models.CharField(max_length=50, blank=True, null=True, verbose_name='昵称')
    email = models.EmailField(max_length=100, blank=True, null=True, verbose_name='邮箱')
    gender = models.SmallIntegerField(choices=((0, '男'), (1, '女')), default=0, verbose_name='性别')
    avatar = models.ImageField(upload_to=uuid_file_path_for_avatar, blank=True, null=True, verbose_name='头像')
    desc = models.CharField(max_length=500, blank=True, null=True, verbose_name='个人描述')
    isAdmin = models.BooleanField(default=0, verbose_name='是否为管理员')

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []  # 根据需要添加其他必填字段

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    def get_absolute_url(relative_path):
        return settings.BASE_URL + relative_path

    def save(self, *args, **kwargs):
        # 如果有新的图片上传，则更新图片路径为完整的 URL
        if self.avatar:
            print(uuid_file_path(self, self.avatar.name)) 
        super().save(*args, **kwargs)


class Topic(models.Model):
    t_uid = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics', verbose_name='发帖用户', null=False, blank=False)
    t_title = models.CharField(max_length=200, verbose_name='帖子标题')
    t_content = models.TextField(verbose_name='帖子内容')
    t_kind = models.TextField()
    create_time = models.BigIntegerField(verbose_name='发帖时间戳')
    t_photo = models.ImageField(upload_to=uuid_file_path, null=True, blank=True, verbose_name='帖子图片')
    t_introduce = models.CharField(max_length=500, null=True, blank=True, verbose_name='帖子简介')
    recommend = models.BooleanField(default=False, verbose_name='是否推荐')

    class Meta:
        verbose_name = '帖子'
        verbose_name_plural = verbose_name
        ordering = ('-create_time',)

    def __str__(self):
        return self.t_title
    
    def get_absolute_url(relative_path):
        return settings.BASE_URL + relative_path
    
    def save(self, *args, **kwargs):
        # 如果 t_create_time 为空，则将当前时间转换为时间戳并保存
        if not self.create_time:
            self.create_time = int(time.time())

        # 如果有新的图片上传，则更新图片路径为完整的 URL
        if self.t_photo:
            print(uuid_file_path(self, self.t_photo.name)) 
        super().save(*args, **kwargs)


class Announcement(models.Model):
    a_uid = models.ForeignKey(User, on_delete=models.CASCADE, related_name='announcements')
    a_content = models.TextField()
    a_create_time = models.IntegerField(verbose_name='公告时间戳')

    def __str__(self):
        return f'Announcement by {self.a_uid.username} at {self.a_create_time}'
    
    def save(self, *args, **kwargs):
            # 如果 a_create_time 为空，则将当前时间转换为时间戳并保存
            if not self.a_create_time:
                self.a_create_time = int(time.time())
            super().save(*args, **kwargs)
